package com.huluobo.a2202mvvm_im_douyindemo.register;

import android.text.TextUtils;
import android.widget.Toast;

import com.huluobo.a2202mvvm_im_douyindemo.IMApp;
import com.huluobo.a2202mvvm_im_douyindemo.R;
import com.huluobo.a2202mvvm_im_douyindemo.databinding.ActivityRegisterBinding;
import com.huluobo.a2202mvvm_im_douyindemo.mvvmBase.BaseMVVMActivity;

public class RegisterActivity extends BaseMVVMActivity<ActivityRegisterBinding, RegisterViewModel> {

    @Override
    protected void initData() {
        viewModel.success.observe(this, loginUserBean -> {
            dismissProgressDialog();
            Toast.makeText(this, "注册成功:" + loginUserBean.getUsername(), Toast.LENGTH_SHORT).show();
            finish();
        });

        viewModel.failed.observe(this, s -> {
            dismissProgressDialog();
            if (s == 203) {
                Toast.makeText(this, "用户名已存在", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "注册失败:" + s, Toast.LENGTH_SHORT).show();
            }
        });
    }

    @Override
    protected void intiView() {
        dataBinding.registerHeader.headerTitleTv.setText("注册");
        dataBinding.reigsterToRegisterBtn.setOnClickListener(v -> {
            String usernameString = dataBinding.registerUsernameEt.getText().toString();
            String passwordString = dataBinding.registerPasswordEt.getText().toString();
            String rePasswordString = dataBinding.registerRePassword.getText().toString();

            if (!usernameString.matches(IMApp.REGEX_USERNAME)) {
                dataBinding.registerUsernameEt.setError("用户名不匹配,需要3-20位字符,首字符为英文");
                return;
            }

            if (!passwordString.matches(IMApp.REGEX_PASSWORD)) {
                dataBinding.registerPasswordEt.setError("密码不匹配,需要3-20位数字");
                return;
            }

            if (TextUtils.equals(passwordString, rePasswordString)) {
                viewModel.register(usernameString, passwordString);
                showProgressDialog("正在注册...");
            } else {
                dataBinding.registerRePassword.setError("两次密码输入不一致");
            }
        });
    }

    @Override
    protected Class<RegisterViewModel> getViewModel() {
        return RegisterViewModel.class;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_register;
    }
}